package com.espirit.eap.sa;

import java.util.ArrayList;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.security.LoginCallback;
import com.googlecode.cswish.security.SafeManager;
import com.googlecode.cswish.security.auth.UserInfo;
import com.googlecode.cswish.struts.ContextHolder;
import com.googlecode.cswish.struts.Initialization;

@Service
public class UserService extends UserServiceSupport implements Initialization{

	private final static Log logger = LogFactory.getLog(UserService.class);

	private UserService userService;

	public UserService getUserService() {
		if (userService == null) {
			userService = objectFactory.getBean(UserService.class, false);
		}
		return userService;
	}

	public UserService() {
		commonPermitPath = new ArrayList<String>();

		// mock a free path for all the @Rest(simpleServiceName="loginUser",
		// type="free")
		commonPermitPath.add("/loginUser.free.html");

		commonPermitPath.add("/espirit/i18n.html");
		commonPermitPath.add("/espirit/header.html");
		commonPermitPath.add("/espirit/test.html");

		commonPermitPath.add("/espirit/common/message.blank.html");
	}

	@PostConstruct
	private void init() {
		functions.registCommonService("user", this);

		//
		userCache = cacheService.newCache(String.class);
	}

	final String[] productName = new String[] {"hr"};
	@Override
	public String[] getProductName() {
		return productName;
	}

	@Override
	public void initSite() {
		safeManager.setLoginCallback(new LoginCallback() {
			@Override
			public UserInfo execute(SafeManager safeManager, String userId, String site) {
				ContextHolder context = ContextHolder.get();
				String oldSite = context.getSiteName();
				try {
					context.setSiteName(site);
					UserInfo userInfo = getUserService().loginUserBySite(userId, site);
					return userInfo;
				} finally {
					// restore site
					context.setSiteName(oldSite);
				}
			}
		});
	}

}
